using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WebApi001.Controllers;
using WebApi001.Domain.Entity;
using WebApi001.inetrface.Data;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebApi001
{
  [Route("api/[controller]")]
  public class RolesController : Controller
  {
    private readonly IRespository<Roles> _rolesRes;
    private readonly IRespository<RolesPermission> _rolePermissionRes;

    public RolesController(IRespository<Roles> rolesRes, IRespository<RolesPermission> rolePermissionRes)
    {
      _rolesRes = rolesRes;
      _rolePermissionRes = rolePermissionRes;
    }
    // GET: api/<controller>
    [HttpGet]
    public ActionResult Get()
    {
      var list = _rolesRes.Table
        .Where(x => x.IsActived == true && x.IsDeleted == false)
        .ToList();
      return Ok(new { code = 20000, data = list, msg = "获取用户信息成功！" });
    }

    // GET api/<controller>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
      return "value";
    }

    // POST api/<controller>
    [HttpPost]
    public ActionResult Post([FromBody]Roles request)
    {
      var item = new Roles
      {
        RolesName = request.RolesName,
        Description = request.Description
      };
      _rolesRes.Add(item);
      return Ok(new { code = 20000, data = item, msg = "用户添加成功！" });
    }

    // PUT api/<controller>/5
    [HttpPut("{id}")]
    public ActionResult Put(int id, [FromBody]Roles request)
    {
      var item = _rolesRes.GetById(id);
      if(item != null)
      {
        item.RolesName = request.RolesName;
        item.Description = request.Description;
        _rolesRes.Update(item);
        return Ok(new { code = 20000, data = "", msg = "用户更新成功！" });
      }
      else
      {
        return Ok(new { code = 20000, data = "", msg = "当前用户不存在！" });
      }

    }

    // DELETE api/<controller>/5
    [HttpDelete("{id}")]
    public ActionResult Delete(int id)
    {
      var item =_rolesRes.GetById(id);
      if(item != null)
      {
        item.IsDeleted = true;
        _rolesRes.Update(item);
        return Ok(new { code = 1000, data = "", msg = "角色删除成功" });
      }
      else
      {
        return Ok(new { code = 1000, data = "", msg = "角色删除失败" });
      }
    }
    [HttpPost,Route("saverolePermission")]
    public ActionResult SaverolePermission([FromBody] RolePermissionDto rolePermission)
    {
      var accessList = new List<RolesPermission>();
      foreach(var item in rolePermission.Access)
      {
        var acc = new RolesPermission
        {
          RolesId = rolePermission.RoleId,
          PermissionName = item.Name,
        };
        accessList.Add(acc);
      }
      _rolePermissionRes.Add(accessList);
      return Ok(new { code = 20000, data = "", msg = "用户登出成功！" });
    }
  }
}
